﻿using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;

using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Text;



namespace FL.DBModule
{
    public class DataTableBaseEntity : BaseEntity, IEnumerable, IEnumerator
    {
        /// <summary>
        /// 数据行
        /// </summary>
        public DataRow DRow
        {
            get;
            set;
        }

        /// <summary>
        /// 
        /// </summary>
        public DataTableBaseEntity() { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="row"></param>
        public DataTableBaseEntity(DataRow row)
        {
            this.DRow = row;
            this.DTable = DRow.Table;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        public DataTableBaseEntity(DataTable dt)
        {
            CreateDT(dt);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        public void CreateDT(DataTable dt)
        {
            this.DTable = dt;
            if (this.DTable.Rows.Count == 0)
            {
                this.DRow = dt.NewRow();
                //this.DRow[TableKey] = Guid.NewGuid();
                this.DTable.Rows.Add(this.DRow);
            }
            else
            {
                this.DRow = dt.Rows[0];
            }
        }

        /// <summary>
        /// 获取配置文件中Confing的相关信息
        /// 用于处理有人工设置界面需要增加自定义信息功能
        /// </summary>
        /// <param name="tableName"></param>
        public void CreateConfigDT(string tableName)
        {
            DataTable dt1 = (new FL.DAL.DbSql()).ExecuteQuery("Select FieldName from Set_EditUIConfig where EntityName='" + tableName+"' and IsSysAutoSave='Y'");
            if (dt1 == null)
            {
                return;
            }
            if (dt1.Rows.Count ==0)
            {
                return;
            }
            string fields= string.Empty;
            foreach (DataRow row in dt1.Rows)
            {
                fields =fields + row.ItemArray[0].ToString()+",";
            }
            fields = fields + this.KeyField;//将关键字付上
            DataTable dt = (new FL.DAL.DbSql()).ExecuteQuery("Select top 0 " + fields + " from " + this.TableName);
            CreateDT(dt);
            this.IsSysAutoSave = true;
        }

        public bool IsSysAutoSave
        {
            get;
            set;
        }


        public void CreateDT()
        {
            DataTable dt = (new  FL.DAL.DbSql()).ExecuteQuery("Select top 0 * from " + this.TableName);
            CreateDT(dt);
        }

        /// <summary>
        /// 复制一个DataTable副本
        /// </summary>
        /// <param name="id"></param>
        public void CreateDT(string id)
        {
            DataTable dt = (new FL.DAL.DbSql()).ExecuteQuery("Select top 1 * from " + this.TableName + " where  "+this.KeyField +"='"+id+"'");
            CreateDT(dt);
        }

        public bool Delete(string id)
        {
           BaseEntityDataContext  context = new BaseEntityDataContext(this);
           int i = (new FL.DAL.DbSql(context.DbConnention, context.DbType)).RunSqlCommand("Delete from " + this.TableName + " where  " + this.KeyField + "='" + id + "'");
            return i > 0;
            //return false;
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        public override string GetTableKeyField()
        {
            object[] o = new object[1];
            o[0] = this;
            object instance = CreateInstance("FL.Bussiness.BaseBussnies", "FL.Bussiness", o);
            
            Type t = instance.GetType();
            object obj = t.InvokeMember("GetKeyField", BindingFlags.Default | BindingFlags.InvokeMethod
                        , null, instance, null);
            return obj as string;
        }






        /// <summary>
        /// 将数据装入字典
        /// </summary>
        /// <returns></returns>
        public SortedDictionary<string, object> GetFieldValueList()
        {
            SortedDictionary<string, object> dic = new SortedDictionary<string, object>();
            for (int i = 0; i <DTable.Columns.Count;i++ )
            {
                string field = DTable.Columns[i].ColumnName;
                string fieldType = DTable.Columns[i].DataType.FullName;
                if (fieldType == "System.Guid")
                {
                    if (DRow[field].ToString() == "")
                    {
                        DRow[field] = Guid.Empty;    
                    }
                }
                if (fieldType == "System.DateTime")
                {
                    if (DRow[field].ToString() == "")
                    {
                        DRow[field] = "1900-01-01";
                    }
                }

                if (fieldType == "System.Decimal")
                {
 
                        System.Decimal _d ;
                        System.Decimal.TryParse(DRow[field].ToString(),out _d);
                        DRow[field] = _d;

                }


                if (fieldType == "System.Double")
                {

                        System.Double _d;
                        System.Double.TryParse(DRow[field].ToString(), out _d);
                        DRow[field] = _d;

                }

                if (fieldType.ToLower().Contains("int"))
                {
                    System.Int32 _d;
                    System.Int32.TryParse(DRow[field].ToString(), out _d);
                    DRow[field] = _d;
                }

                dic.Add(field, DRow[field]);
            }
            return dic;
        }

        /// <summary>
        /// 获取DT结构
        /// </summary>
        /// <returns></returns>
        public SortedDictionary<string, object> GetFiledList()
        {
            SortedDictionary<string, object> dic = new SortedDictionary<string, object>();
            for (int i = 0; i < DTable.Columns.Count; i++)
            {
                string field = DTable.Columns[i].ColumnName;
                dic.Add(field, DTable.Columns[i].DataType.ToString());
            }
            return dic;
        }

        public Dictionary<string, object> FieldValue
        {
            get;
            set;
        }

        public string _SubRows
        {
            get;
            set;
        }
        /// <summary>
        /// 设列值
        /// </summary>
        /// <param name="key">列名</param>
        /// <param name="value">值</param>
        public virtual void SetValue(string key, object value)
        {
            DRow[key] = value==null?DBNull.Value:value;
        }


        public virtual void SetValue(Dictionary<string, object> fieldValue)
        {
            SortedDictionary<string, object> list = GetFiledList();
            foreach (var item in fieldValue)
            {
                if (!list.ContainsKey(item.Key))
                {
                    continue;
                }
                string fType = list[item.Key] as string;
                object o = item.Value;
                switch (fType)
                {
                    case "System.String":
                        o = item.Value;
                        break;
                    case "System.Decimal":
                        try
                        {
                            o = System.Decimal.Parse(item.Value.ToString());
                        }
                        catch { o = 0.0; }
                        break;
                    case "System.Int32":
                        try
                        {
                            o = System.Int32.Parse(item.Value.ToString());
                        }
                        catch { o = 0; }
                        break;
                    case "System.Int16":
                        try
                        {
                            o = System.Int32.Parse(item.Value.ToString());
                        }
                        catch { o = 0; }
                        break;
                    case "System.DateTime":
                        try
                        {
                            o = System.DateTime.Parse(item.Value.ToString());
                        }
                        catch { o = System.DateTime.Parse("1900-01-01"); }
                        break;
                    case "System.Guid":
                        try
                        {
                            if ((item.Value as string) == "")
                            {
                                o = Guid.NewGuid();
                            }
                            else
                            {
                                o = System.Guid.Parse(item.Value.ToString());
                            }
                        }
                        catch { o = Guid.Empty; }
                        break;
                    case "System.Int64":
                        try
                        {
                            o = System.Int64.Parse(item.Value.ToString());
                        }
                        catch { o = 0.0; }
                        break;
                    case    "System.Boolean":
                        try
                        {
                            o = System.Boolean.Parse(item.Value.ToString());
                        }
                        catch { o = false; }
                        break;
                    case "System.Double":
                        try
                        {
                            o = System.Double.Parse(item.Value.ToString());
                        }
                        catch { o = 0; }
                        break;
 
                    default:
                        break;
                }
                SetValue(item.Key, o);
            }
        }



        public object this[string key]
        {
            get
            {
                if (DRow[key] == null)
                {
                    throw new Exception("不存在列名:" + key);
                }
                return DRow[key];
            }
            set
            {
                if (DRow[key] != this[key])
                {
                    DRow[key] = this[key];
                }
            }
        }
        

        /// <summary>
        /// 实体对应的JSON
        /// </summary>
        public string EntityJson
        {
            get;
            set;
        }


        public DataTable DTable
        {
            get;
            set;
        }


        public void AddColums(string field, string dataType)
        {
            switch (dataType)
            {
                case "string":
                    DTable.Columns.Add(field, Type.GetType("System.String"));
                    break;
                case "guid":
                    DTable.Columns.Add(field, Type.GetType("System.Guid"));
                    break;
                case "datetime":
                    DTable.Columns.Add(field, Type.GetType("System.DateTime"));
                    break;
                case "int":
                    DTable.Columns.Add(field, Type.GetType("System.Int32"));
                    break;
                case "long":
                    DTable.Columns.Add(field, Type.GetType("System.Int64"));
                    break;
                case "bool":
                    DTable.Columns.Add(field, Type.GetType("System.Boolean"));
                    break;
                case "number":
                    DTable.Columns.Add(field, Type.GetType("System.Double"));
                    break;
                default:
                    DTable.Columns.Add(field, Type.GetType("System.String"));
                    break;

            }
        }

        public DataTable DataTableNew()
        {
            return new DataTable();
        }


        /// <summary>
        /// 表KEY
        /// </summary>
        private string _keyField;
        public string KeyField
        {
            get {
                //if (_keyField == null || _keyField == "")
                //{
                //    _keyField = GetTableKeyField();
                //}
                return _keyField;
            }
            set
            {
                _keyField = value;
            }
        }

        /// <summary>
        /// Key的数据类型
        /// </summary>
        public string KeyFieldDataType
        {
            get;
            set;
        }
        /// <summary>
        /// 表名
        /// </summary>
        public string TableName
        {
            get;
            set;
        }


        /// <summary>
        /// Key值为Guid
        /// </summary>
        public Guid TableGuidKey
        {
            get
            {

                if (DRow[KeyField].ToString().IndexOf("-") > -1)
                {
                    return Guid.Parse(DRow[KeyField].ToString());
                }
                return Guid.NewGuid();
            }
        }


        /// <summary>
        /// Key值为int时
        /// </summary>
        public int TableIntKey
        {
            get
            {
                if (DRow[KeyField].ToString().IndexOf("-") < 0)
                {
                    return int.Parse(DRow[KeyField].ToString());
                }
                return 0;
            }
        }

        /// <summary>
        /// 记录数
        /// </summary>
        public int Count
        {
            get
            {
                return DTable == null ? 0 : DTable.Rows.Count;
            }
        }

        public IEnumerator GetEnumerator()
        {
            return (IEnumerator)this;
        }

        public int _Current = 0;
        public object Current
        {
            get
            {
                return new DataTableBaseEntity(DTable.Rows[_Current]);
            }
        }

        public bool MoveNext()
        {
            if (_Current < DTable.Rows.Count - 1 && DTable.Rows.Count >= 1)
            {
                _Current++;
                return true;
            }
            else
            {
                _Current = -1;
                return false;
            }
        }

        public void Reset()
        {
            _Current = -1;
        }

    }
}
